<?php

namespace addons\weixin\controller;

use app\common\library\Auth;
use addons\weixin\library\WechatService;
use app\admin\model\weixin\User as WechatUser;
use think\Hook;
use think\Cookie;

/**
 * 微信公众号接口
 */
class Index extends \think\addons\Controller
{

    public $auth = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->auth = $auth = Auth::instance();

        //监听注册登录注销的事件
        Hook::add('user_login_successed', function ($user) use ($auth) {
            $expire = input('post.keeplogin') ? 30 * 86400 : 0;
            Cookie::set('uid', $user->id, $expire);
            Cookie::set('token', $auth->getToken(), $expire);
        });
    }


    /**
     * @notes 微信公众号授权登录和jssdk分享演示(http://你的域名/addons/weixin)
     * @author 兴
     * @date 2022/10/31 22:58
     */
    public function index()
    {
        //token
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        //初始化
        $this->auth->init($token);
        //检测是否登录
        if (!$this->auth->isLogin()) {
            $this->login();
        }

        $wxModel = new \app\admin\model\weixin\Config();
        $wxConfigData = $wxModel->where([
            'group' => 'weixin', 'name' => ['in', 'share_title,share_img,share_synopsis,avatar']
        ])->select();
        $wxConfig = [];
        foreach ($wxConfigData as $val) {
            $wxConfig[$val['name']] = $val['value'];
        }
        $wxConfig['debug'] = false;

        try {
            $currentUrl = request()->url(true);
            $jsSdk = WechatService::jsSdk(urldecode($currentUrl));
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $jsSdk['jsApiList'] = json_encode($jsSdk['jsApiList']);
        $this->assign('wxConfig', array_merge($wxConfig, $jsSdk));
        $this->assign('currentUrl', $currentUrl);
        return $this->fetch();
    }

    /**
     * 微信公众号服务接口
     * http://你的域名/addons/weixin/index/serve
     */
    public function serve()
    {
        ob_clean();
        return WechatService::serve();
    }

    /**
     * @notes 微信公众号发起授权
     * @author 兴
     * @date 2022/10/31 21:54
     */
    public function login()
    {
        //回调地址
        $return_url = "{$_SERVER['REQUEST_SCHEME']}://" . $_SERVER['HTTP_HOST'] . "/addons/weixin/index/auth";
        //发起授权
        return WechatService::oauthService()->redirect($return_url)->send();
    }

    /**
     * 公众号授权回调登陆
     * http://你的域名/addons/weixin/index/auth
     */
    public function auth()
    {
        try {
            $wechatInfo = WechatService::oauthService()->user()->getOriginal();
        } catch (\Exception $e) {
            $this->error('授权登录失败：' . $e->getMessage());
        }

        $spreadId   = intval($this->request->param('spread'));
        $login_type = $this->request->param('login_type', '');

        //授权成功后
        $uid = WechatUser::onWechatOauthAfter($wechatInfo, $spreadId, $login_type);

        //登录
        $ret = $this->auth->direct($uid);
        if ($ret) {
            $this->success('授权登录成功', url('addons/weixin/index'));
        } else {
            $this->error($this->auth->getError());
        }
    }
}
